﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

using CloudSoft.Workflows;

namespace ERPStore.NewsLetters.Workflows.Activities
{

	public sealed class SendNewsLetter : CodeActivity
	{
		public InArgument<Models.PendingItem> PendingRequestItem { get; set; }

		protected override void Execute(CodeActivityContext context)
		{
			var item = context.GetValue(this.PendingRequestItem);
			var newsLettersService = context.GetService<Services.NewsLettersService>();
			var eventPublisher = context.GetService<ERPStore.Services.IEventPublisher>();

			string reason = null;
			try
			{
				newsLettersService.SendEmail(item);
			}
			catch (Exception ex)
			{
				reason = ex.ToString();
			}

			eventPublisher.AsyncPublish(new Events.NewsLetterSentEventMessage()
			{
				CampaignId = item.CampaignId,
				EmailRecipientId = item.EmailRecipientId,
				FaultReason = reason,
			});

			try
			{
				newsLettersService.DeletePendingRequestItem(item);
			}
			catch(Exception ex)
			{

			}

		}
	}
}
